package com.meida.archive.admin.flyway;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;


@Configuration
@Slf4j
public class FlywayConfig {
    @Autowired
    private DataSource dataSource;
    @Value("${spring.flyway.table}")
    private String table;
    @Value("${spring.flyway.locations}")
    private String locations;
    @Value("${spring.flyway.baseline-on-migrate}")
    private boolean baselineOnMigrate;
    @Value("${spring.flyway.clean-on-validation-error}")
    private boolean cleanOnValidationError;
    @Value("${spring.flyway.placeholder-replacement}")
    private boolean placeholderReplacement;
    @Value("${spring.flyway.enabled}")
    private boolean enabled;

    @PostConstruct
    public void migrate() {
        if (enabled) {
            Flyway flyway = Flyway.configure()
                    .dataSource(dataSource)
                    .table(table)
                    .locations(locations)
                    .baselineOnMigrate(baselineOnMigrate)
                    .cleanOnValidationError(cleanOnValidationError)
                    .placeholderReplacement(placeholderReplacement)
                    .load();
            flyway.migrate();
        }
    }
}
